import React, { useState, useEffect, useRef } from 'react';
import { Table, Spin, message, Input, Button, Modal, Tooltip } from 'antd';
import axios from 'axios';
import { API_BASE_URL } from '../config';
import { LeftOutlined, RightOutlined, SyncOutlined } from '@ant-design/icons';

// 特征定义组件的样式
const featureDefinitionStyles = `
  .feature-list-container {
    height: 100%;
    background-color: #fff;
    border-radius: 4px;
    overflow: hidden;
    box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
  }
  
  .data-table {
    width: 100%;
  }
  
  .table-row-normal-height td {
    padding: 16px 8px;
  }
  
  .table-row-compact-height td {
    padding: 8px;
  }
  
  .compact-table .ant-table-thead > tr > th {
    padding: 8px;
  }
  
  .pagination-container {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 16px;
    border-top: 1px solid #e8e8e8;
  }
  
  .table-header-actions {
    padding: 16px;
    display: flex;
    justify-content: flex-end;
  }
  
  .action-buttons {
    display: flex;
    gap: 8px;
  }
  
  @media (max-width: 576px) {
    .feature-list-container {
      margin: 0;
      border-radius: 0;
    }
  }
`;

// 特征定义列表组件
const FeatureDefinition = () => {
  const [loading, setLoading] = useState(false);
  const [featureList, setFeatureList] = useState([]);
  const [allFeatures, setAllFeatures] = useState([]);
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0
  });
  const [isMobile, setIsMobile] = useState(false);
  const [currentPage, setCurrentPage] = useState(1);
  const [pageSize, setPageSize] = useState(10);
  const inputRef = useRef(null);
  const [syncModalVisible, setSyncModalVisible] = useState(false);
  const [syncLoading, setSyncLoading] = useState(false);
  const [syncResult, setSyncResult] = useState(null);

  // 检测是否为移动设备
  useEffect(() => {
    const checkIsMobile = () => {
      setIsMobile(window.innerWidth <= 576);
    };
    
    checkIsMobile();
    window.addEventListener('resize', checkIsMobile);
    
    return () => {
      window.removeEventListener('resize', checkIsMobile);
    };
  }, []);

  // 获取特征定义列表
  useEffect(() => {
    fetchFeatureDefinitions();
  }, []);

  // 更新当前页数据
  useEffect(() => {
    if (allFeatures.length > 0) {
      updatePageData(allFeatures, currentPage);
    }
  }, [currentPage, pageSize, allFeatures]);

  /**
   * 获取特征定义列表
   * 通过循环调用API获取所有特征数据
   * 接口使用skip和limit参数进行分页
   * skip表示要跳过的记录数，不是页码
   */
  const fetchFeatureDefinitions = async () => {
    setLoading(true);
    try {
      let allItems = [];
      let skip = 0;
      const limit = 20; // 每次获取20条数据
      let hasMore = true;
      
      // 循环调用API，直到获取所有数据
      while (hasMore) {
        const response = await axios.get(`${API_BASE_URL}/api/feature_definition`, {
          params: {
            skip: skip,
            limit: limit
          }
        });
        
        if (response.data && response.data.code === 200) {
          const items = response.data.data.items || [];
          const total = response.data.data.total || 0;
          
          // 合并结果
          allItems = [...allItems, ...items];
          
          // 更新skip，用于下一次请求
          skip += limit;
          
          // 判断是否还有更多数据
          hasMore = allItems.length < total;
          
          console.log(`已获取 ${allItems.length} / ${total} 条特征定义数据`);
          
          if (!hasMore) {
            message.success(`成功获取全部 ${total} 条特征定义数据`);
          }
        } else {
          message.error('获取特征定义列表失败: ' + (response.data.message || '未知错误'));
          hasMore = false;
        }
      }
      
      console.log('全部特征定义列表:', allItems);
      
      // 保存所有特征数据
      setAllFeatures(allItems);
      
      // 更新分页信息
      setPagination({
        ...pagination,
        total: allItems.length
      });
      
      // 手动实现分页
      updatePageData(allItems, currentPage);
    } catch (error) {
      console.error('获取特征定义列表错误:', error);
      message.error('获取特征定义列表失败: ' + (error.message || '网络错误'));
    } finally {
      setLoading(false);
    }
  };

  // 手动分页处理
  const updatePageData = (data, page) => {
    const startIndex = (page - 1) * pageSize;
    const endIndex = startIndex + pageSize;
    const currentPageData = data.slice(startIndex, endIndex);
    setFeatureList(currentPageData);
  };

  // 处理页码变化
  const handlePageChange = (page) => {
    setCurrentPage(page);
  };

  // 处理页码输入
  const handlePageInputChange = (e) => {
    const value = parseInt(e.target.value, 10);
    if (!isNaN(value) && value > 0 && value <= Math.ceil(pagination.total / pageSize)) {
      setCurrentPage(value);
    }
  };

  // 处理页码输入框按键事件
  const handlePageInputKeyPress = (e) => {
    if (e.key === 'Enter') {
      const value = parseInt(e.target.value, 10);
      if (!isNaN(value) && value > 0 && value <= Math.ceil(pagination.total / pageSize)) {
        setCurrentPage(value);
      }
    }
  };

  // 前一页
  const goPrevPage = () => {
    if (currentPage > 1) {
      setCurrentPage(currentPage - 1);
    }
  };

  // 后一页
  const goNextPage = () => {
    if (currentPage < Math.ceil(pagination.total / pageSize)) {
      setCurrentPage(currentPage + 1);
    }
  };

  // 格式化日期
  const formatDate = (dateString) => {
    if (!dateString) return '-';
    
    try {
      const date = new Date(dateString);
      return date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit',
        hour12: false
      });
    } catch (e) {
      return dateString;
    }
  };

  // 显示特征同步确认对话框
  const showSyncConfirm = () => {
    setSyncModalVisible(true);
  };

  // 执行特征同步
  const handleSyncFeatures = async () => {
    setSyncLoading(true);
    setSyncResult(null);
    
    try {
      const response = await axios.get(`${API_BASE_URL}/api/recommendation/sync_features`);
      
      if (response.data && response.data.code === 200) {
        console.log('特征同步结果:', response.data.data);
        setSyncResult(response.data.data);
        message.success('特征同步成功');
        fetchFeatureDefinitions(); // 重新加载特征列表
      } else {
        message.error('特征同步失败: ' + (response.data.message || '未知错误'));
      }
    } catch (error) {
      console.error('特征同步错误:', error);
      message.error('特征同步失败: ' + (error.message || '网络错误'));
    } finally {
      setSyncLoading(false);
    }
  };

  // 关闭同步对话框
  const handleSyncCancel = () => {
    setSyncModalVisible(false);
    setSyncResult(null);
  };

  // 获取表格列定义
  const getColumns = () => {
    const baseColumns = [
      {
        title: '特征编码',
        dataIndex: 'feature_code',
        key: 'feature_code',
        align: 'center',
        ellipsis: true,
        render: (text) => <span>{text || '-'}</span>
      },
      {
        title: '特征名称',
        dataIndex: 'feature_name',
        key: 'feature_name',
        align: 'left',
        ellipsis: true,
        render: (text) => <span>{text || '-'}</span>
      },
      {
        title: '特征类型',
        dataIndex: 'feature_type',
        key: 'feature_type',
        align: 'center',
        ellipsis: true,
        render: (text) => <span>{text || '-'}</span>
      },
      {
        title: '数据类型',
        dataIndex: 'data_type',
        key: 'data_type',
        align: 'center',
        ellipsis: true,
        render: (text) => <span>{text || '-'}</span>
      },
      {
        title: '提取方法',
        dataIndex: 'extraction_method',
        key: 'extraction_method',
        align: 'center',
        ellipsis: true,
        render: (text) => <span>{text || '-'}</span>
      },
      {
        title: '描述',
        dataIndex: 'description',
        key: 'description',
        align: 'left',
        ellipsis: true,
        render: (text) => <span>{text || '-'}</span>
      },
      {
        title: '创建时间',
        dataIndex: 'create_time',
        key: 'create_time',
        align: 'center',
        ellipsis: true,
        render: (text) => <span>{formatDate(text)}</span>
      },
      {
        title: '更新时间',
        dataIndex: 'update_time',
        key: 'update_time',
        align: 'center',
        ellipsis: true,
        render: (text) => <span>{formatDate(text)}</span>
      }
    ];
    
    // 移动端只显示核心列
    if (isMobile) {
      return baseColumns.filter(column => 
        ['feature_code', 'feature_name', 'feature_type'].includes(column.key)
      );
    }
    
    return baseColumns;
  };

  // 获取行样式
  const getRowClassName = () => {
    if (featureList.length >= 10 || isMobile) {
      return "table-row-compact-height";
    }
    return "table-row-normal-height";
  };

  // 自定义分页样式
  const customPaginationStyle = {
    display: 'flex',
    justifyContent: 'space-between',
    alignItems: 'center',
    padding: '16px',
    borderTop: '1px solid #e8e8e8',
    background: '#fff'
  };

  return (
    <Spin spinning={loading}>
      <style dangerouslySetInnerHTML={{ __html: featureDefinitionStyles }} />
      <div className="feature-list-container" style={{ height: '100%', display: 'flex', flexDirection: 'column' }}>
        <div className="table-header-actions">
          <div className="action-buttons">
            <Tooltip title="同步最新特征数据">
              <Button 
                type="primary"
                icon={<SyncOutlined />}
                onClick={showSyncConfirm}
              >
                特征同步
              </Button>
            </Tooltip>
          </div>
        </div>
        
        <div style={{ flex: 1, overflow: 'auto' }}>
          <Table
            className={`data-table ${featureList.length >= 10 || isMobile ? 'compact-table' : ''}`}
            dataSource={featureList}
            columns={getColumns()}
            rowKey="id"
            pagination={false}
            rowClassName={getRowClassName}
            size={isMobile || featureList.length >= 10 ? 'small' : 'middle'}
            bordered={true}
            scroll={{ x: isMobile ? 800 : 'max-content' }}
            tableLayout="auto"
            locale={{ emptyText: '暂无数据' }}
          />
        </div>
        
        {/* 自定义分页 */}
        <div style={customPaginationStyle} className="pagination-container">
          <div style={{ display: 'flex', alignItems: 'center' }}>
            <span>共 {pagination.total} 条，{Math.ceil(pagination.total / pageSize)} 页</span>
          </div>
          
          <div style={{ display: 'flex', alignItems: 'center' }}>
            <Button 
              icon={<LeftOutlined />}
              onClick={goPrevPage}
              disabled={currentPage === 1}
              style={{ marginRight: '8px' }}
            />
            
            <Input
              ref={inputRef}
              style={{ width: '50px', textAlign: 'center', margin: '0 8px' }}
              value={currentPage}
              onChange={handlePageInputChange}
              onKeyPress={handlePageInputKeyPress}
            />
            
            <span style={{ margin: '0 8px' }}>/ {Math.ceil(pagination.total / pageSize)}</span>
            
            <Button 
              icon={<RightOutlined />}
              onClick={goNextPage}
              disabled={currentPage >= Math.ceil(pagination.total / pageSize)}
              style={{ marginLeft: '8px', marginRight: '8px' }}
            />
            
            <span style={{ marginLeft: '8px' }}>
              {pageSize} / page
            </span>
          </div>
        </div>
      </div>

      {/* 特征同步确认对话框 */}
      <Modal
        title="特征同步"
        open={syncModalVisible}
        onOk={syncResult ? handleSyncCancel : handleSyncFeatures}
        confirmLoading={syncLoading}
        okText={syncResult ? "确认" : "开始同步"}
        footer={syncResult ? [
          <Button key="ok" type="primary" onClick={handleSyncCancel}>
            确认
          </Button>
        ] : [
          <Button key="cancel" onClick={handleSyncCancel}>
            取消
          </Button>,
          <Button key="submit" type="primary" loading={syncLoading} onClick={handleSyncFeatures}>
            开始同步
          </Button>
        ]}
        closable={false}
        maskClosable={false}
        width={500}
      >
        <Spin spinning={syncLoading}>
          {!syncResult ? (
            <div>
              <p>特征同步将从产品和模板数据中提取最新特征，并更新到推荐系统中。</p>
              <p>此操作可能需要一些时间，确认开始同步吗？</p>
            </div>
          ) : (
            <div>
              <h3 style={{ color: '#1766a3', marginBottom: '16px' }}>同步结果</h3>
              <div style={{ marginBottom: '8px' }}>
                <span style={{ fontWeight: 'bold', marginRight: '8px' }}>同步状态:</span>
                <span style={{ color: syncResult.success ? '#52c41a' : '#f5222d' }}>
                  {syncResult.success ? '成功' : '失败'}
                </span>
              </div>
              <div style={{ marginBottom: '8px' }}>
                <span style={{ fontWeight: 'bold', marginRight: '8px' }}>同步时间:</span>
                <span>{formatDate(syncResult.sync_time)}</span>
              </div>
              <div style={{ marginBottom: '8px' }}>
                <span style={{ fontWeight: 'bold', marginRight: '8px' }}>产品特征数量:</span>
                <span>{syncResult.product_features_count}</span>
              </div>
              <div style={{ marginBottom: '8px' }}>
                <span style={{ fontWeight: 'bold', marginRight: '8px' }}>模板特征数量:</span>
                <span>{syncResult.template_features_count}</span>
              </div>
              <div style={{ marginBottom: '8px' }}>
                <span style={{ fontWeight: 'bold', marginRight: '8px' }}>同步信息:</span>
                <span>{syncResult.message}</span>
              </div>
            </div>
          )}
        </Spin>
      </Modal>
    </Spin>
  );
};

export default FeatureDefinition; 